<?php
namespace app\api\controller;

use think\Cache;
use think\Config;
use think\Db;
use think\Request;


class Command extends Common
{
    public function index()
    {

        
        //Cache::set('syncOracleQueueHis' . 7,1,0); 
        //同步历史
        $syncQueueHisTime = Cache::get('syncOracleQueueHis' . 7);echo $syncQueueHisTime;die;
	    $this->getOracleDb(7);
        if (($syncQueueHisTime && NOW_TIME - $syncQueueHisTime > Config::get('syncTime'))) {
            $syncQueueHisTime = $syncQueueHisTime ?: '0';
            $lastQueueHisDate = date('Y-m-d H:i:s', $syncQueueHisTime);

            $sql = "select ID, CODE, SERVICE,to_char(FCD,'yyyy-mm-dd hh24:mi:ss') FCDFORMATE, " .
                "to_char(SSD,'yyyy-mm-dd hh24:mi:ss') SSDFORMATE,to_char(LCD,'yyyy-mm-dd hh24:mi:ss') LCDFORMATE " .
                " from QUEUE_HISTORY where LCD>to_date('" . $lastQueueHisDate . "','yyyy-mm-dd hh24:mi:ss') and rownum<=200 ORDER BY LCD asc ";
            $syncQueueHisLists = $this->oracleDb->query($sql);
print_r($syncQueueHisLists);die;
            if ($syncQueueHisLists) {
                $queueHisModel = model('QueueHistory');
                $queueModel = model('Queue');
                foreach ($syncQueueHisLists as $key => $syncQueueHisList) {
                    $insertQueue = $queueHisModel->field(true)->where(['queue_sn' => $syncQueueHisList['ID']])->find();
                    $queueInfo = $queueModel->where('queue_sn', $syncQueueHisList['ID'])->find();
                    $lcdTime = strtotime($syncQueueHisList['LCDFORMATE']);

                    if (!$insertQueue) {//mysql 历史队列里不存在

                        $queueHisData = array(
                            'queue_sn' => $syncQueueHisList['ID'],
                            'queue_code' => $syncQueueHisList['CODE'],
                            'branchid' => isset($queueInfo->branchid) ? $queueInfo->branchid : $branchId,
                            'serviceid' => isset($queueInfo->bisid) ? $this->getLocalServiceId($queueInfo->branchid, $syncQueueHisList['SERVICE']) : 1,
                            'bisid' => isset($queueInfo->bisid) ? $queueInfo->bisid : 0,
                            'type' => isset($queueInfo->type) ? $queueInfo->type : 3,  //线下排队
                            'uid' => isset($queueInfo->uid) ? $queueInfo->uid : 0,
                            'truename' => isset($queueInfo->truename) ? $queueInfo->truename : 0,
                            'mobile' => isset($queueInfo->mobile) ? $queueInfo->mobile : 0,
                            'queue_time' => strtotime($syncQueueHisList['FCDFORMATE']),
                            'handle_start_time' => strtotime($syncQueueHisList['SSDFORMATE']),
                            'handle_end_time' => $lcdTime,
                            'create_time' => NOW_TIME
                        );
                        $queueHisData['queue_status'] = $queueHisData['handle_start_time'] == $queueHisData['handle_end_time'] ? 2 : 3;
                        $boolean = $queueHisModel->insert($queueHisData);
                    } else {
		    
		    print_r($insertQueue);die;
                        $queueHisModel->where(['id' => $insertQueue['id']])->update(['queue_status' => 3, 'handle_end_time' => $lcdTime]);
                    }
                    $queueModel->where('queue_sn', $syncQueueHisList['ID'])->delete();

                }
                Cache::set('syncOracleQueueHis' . 7, $lcdTime, 0);
            }
        }

        die;
//        {"total":4,"rows":[
//                   { "client_id": "A122", "queue_id": "1", "time_enter": "2017-4-1 16:40:48", "time_call": "2017-4-1 16:46:45", "time_leave": "", "worker_id": "109", "wnd_id": "09", "states": "1" },
//                   { "client_id": "A123", "queue_id": "1", "time_enter": "2017-4-1 16:40:52", "time_call": "2017-4-1 16:48:42", "time_leave": "", "worker_id": "103", "wnd_id": "03", "states": "1" },
//                   { "client_id": "A124", "queue_id": "1", "time_enter": "2017-4-1 16:47:17", "time_call": "2017-4-1 16:49:42", "time_leave": "", "worker_id": "110", "wnd_id": "10", "states": "1" },
//                   { "client_id": "A125", "queue_id": "1", "time_enter": "2017-4-1 16:47:20", "time_call": "2017-4-1 16:50:07", "time_leave": "", "worker_id": "108", "wnd_id": "08", "states": "1" }
//                  ]
//         }
//排队叫号表字段说明如下:
//  client_id:排队号码
//  queue_id:队列ID
//  time_enter:取号时间
//  time_call:叫号时间
//  time_leave:业务办结时间
//  worker_id:窗口员工ID
//  wnd_id:窗口ID
//  states:排队号的状态值;0--等待叫号,1--已叫号,3--业务受理中,4--业务已办结.


        $data = [];
        $branchLists = model('BranchList')->where(['isdelete' => 0])->column('id,db_info');
        foreach ($branchLists as $branchId => $branchInfo) {
            // 初次同步 初始化缓存
            if (!Cache::has('syncUploadQueue' . $branchId)) {
                Cache::set('syncUploadQueue' . $branchId, strtotime(date('Y-m-d', NOW_TIME)), 0);
            }

            $syncUploadQueueTime = Cache::get('syncUploadQueue' . $branchId);

            model('');


            Cache::set('syncUploadQueue' . $branchId, NOW_TIME);

        }


//        try {
////        header("content-type:text/html;charset=utf-8");
//            $client = new \SoapClient("http://218.90.169.62:5223/WXGTCloud/Code/DataCenter/WebService.asmx?WSDL", array("trace" => true, "connection_timeout" => 100));
//            $param = array('sessionID' => '5gvMBR03C1Kf7wDhRZp212nTvfJUgc4s2bpUN2WHz896pj6KIx1Fa9kdIqOx2fSN2bV', 'areaName' => '滨湖区', 'windowName' => '滨湖国土分局');
//            $param['jsonContent'] = json_encode($data);
//            //调用必须用__soapCall
//            $p = $client->SendCallerInfo($param);
//        } catch (\SOAPFault $e) {
//            print_r('Exception:' . $e);
//            return null;
//        }

        //参数这样传递 先包装一下
//        var_dump($p); //这里先输出一下变量$p，看看是什么类型。


    }

    /**
     * 同步oracle 与 mysql 数据
     */
    public function syncQueueData()
    {

        $branchLists = model('BranchList')->where(['isdelete' => 0])->column('id,db_info');
//        shuffle($branchLists);
        foreach ($branchLists as $branchId => $branchInfo) {
            echo $branchId;
            // 初次同步 初始化缓存
            if (!Cache::has('syncOracleQueue' . $branchId)) {
                Cache::set('syncOracleQueue' . $branchId, 1, 0);
            }
            // 初次同步 初始化缓存
            if (!Cache::has('syncOracleQueueHis' . $branchId)) {
                Cache::set('syncOracleQueueHis' . $branchId, 1, 0);
            }
            $oracleResult = $this->getOracleDb($branchId);

            if ($this->result['error']) {
                $this->result['error'] = 0;
                continue;
            }

            $syncQueueTime = Cache::get('syncOracleQueue' . $branchId);
//            $syncQueueTime = 1;
            if (($syncQueueTime && NOW_TIME - $syncQueueTime > Config::get('syncTime'))) {
                $syncQueueTime = $syncQueueTime ? $syncQueueTime: '1';
                $lastQueueDate = date('Y-m-d H:i:s', $syncQueueTime);
echo '$lastQueueDate'.$lastQueueDate;

                //同步队列新数据
                $sql = "select ID, SERVICE, CODE, to_char(FCD,'yyyy-mm-dd hh24:mi:ss') FCDFORMATE from QUEUE" .
                    " where FCD>=to_date('" . $lastQueueDate . "','yyyy-mm-dd hh24:mi:ss')";
                $syncQueueLists = $this->oracleDb->query($sql);
//		        print_r($syncQueueLists);die;
                if ($syncQueueLists) {
                    $queueModel = model('Queue');
                    foreach ($syncQueueLists as $key => $syncQueueList) {
                        $insertQueue = $queueModel->field(true)->where(['queue_sn' => $syncQueueList['ID']])->find();

                        if (!$insertQueue) {
                            $boolean = $queueModel->insert([
                                'queue_sn' => $syncQueueList['ID'],
                                'branchid' => $branchId,
                                'serviceid' => $this->getLocalServiceId($branchId, $syncQueueList['SERVICE']),
                                'bisid' => 0,
                                'type' => 3,  //线下排队
                                'queue_time' => strtotime($syncQueueList['FCDFORMATE']),
                                'queue_code' => $syncQueueList['CODE'],
                                'create_time' => NOW_TIME
                            ]);
                        }
                    }
                }

                Cache::set('syncOracleQueue' . $branchId, NOW_TIME, 0);
            }


            //同步历史
            $syncQueueHisTime = Cache::get('syncOracleQueueHis' . $branchId);
            if (($syncQueueHisTime && NOW_TIME - $syncQueueHisTime > Config::get('syncTime'))) {
                $syncQueueHisTime = $syncQueueHisTime ?: '0';
                $lastQueueHisDate = date('Y-m-d H:i:s', $syncQueueHisTime);
                echo '$lastQueueHisDate'.$lastQueueHisDate;
                //$lastQueueHisDate = '2018-03-07 11:14:00';

                $sql = "select ID, CODE, SERVICE,to_char(FCD,'yyyy-mm-dd hh24:mi:ss') FCDFORMATE, " .
                    "to_char(SSD,'yyyy-mm-dd hh24:mi:ss') SSDFORMATE,to_char(LCD,'yyyy-mm-dd hh24:mi:ss') LCDFORMATE " .
                    " from QUEUE_HISTORY where LCD>=to_date('" . $lastQueueHisDate . "','yyyy-mm-dd hh24:mi:ss') and rownum<=200 ORDER BY LCD asc ";
                $syncQueueHisLists = $this->oracleDb->query($sql);
//                print_r($syncQueueHisLists);echo $sql;die;
                if ($syncQueueHisLists) {
                    $queueHisModel = model('QueueHistory');
                    $queueModel = model('Queue');
                    foreach ($syncQueueHisLists as $key => $syncQueueHisList) {
                        $insertQueue = $queueHisModel->field(true)->where(['queue_sn' => $syncQueueHisList['ID']])->find();//print_r($insertQueue);die;
                        $queueInfo = $queueModel->where('queue_sn', $syncQueueHisList['ID'])->find();
                        $lcdTime = strtotime($syncQueueHisList['LCDFORMATE']);
                        if (!$insertQueue) {//mysql 历史队列里不存在

                            $queueHisData = array(
                                'queue_sn' => $syncQueueHisList['ID'],
                                'queue_code' => $syncQueueHisList['CODE'],
                                'branchid' => isset($queueInfo->branchid) ? $queueInfo->branchid : $branchId,
                                'serviceid' => isset($queueInfo->bisid) ? $this->getLocalServiceId($queueInfo->branchid, $syncQueueHisList['SERVICE']) : 1,
                                'bisid' => isset($queueInfo->bisid) ? $queueInfo->bisid : 0,
                                'type' => isset($queueInfo->type) ? $queueInfo->type : 3,  //线下排队
                                'uid' => isset($queueInfo->uid) ? $queueInfo->uid : 0,
                                'truename' => isset($queueInfo->truename) ? $queueInfo->truename : 0,
                                'mobile' => isset($queueInfo->mobile) ? $queueInfo->mobile : 0,
                                'queue_time' => strtotime($syncQueueHisList['FCDFORMATE']),
                                'handle_start_time' => strtotime($syncQueueHisList['SSDFORMATE']),
                                'handle_end_time' => $lcdTime,
                                'create_time' => NOW_TIME
                            );
                            $queueHisData['queue_status'] = $queueHisData['handle_start_time'] == $queueHisData['handle_end_time'] ? 2 : 3;
                            $boolean = $queueHisModel->insert($queueHisData);

                            //更新因为业务员快速按下过号按钮导致mysql监测不到业务办理结束时间和开始时间的差异。有新办理中的业务时，需要将之前的数据状态变为  办理完成
                            if ($queueHisData['queue_status'] == 2) {
                                $queueHisModel->update(['queue_status' => 3], ['queue_sn' => ['neq',$queueHisData['queue_sn']],'branchid' => $branchId, 'serviceid' => $queueHisData['serviceid'], 'handle_end_time' => ['gt', $syncQueueHisTime]]);
                            }

                        } else {
//                            $queueHisModel->where(['id' => $insertQueue['id'],'handle_end_time'=>['neq',$lcdTime]])->update(['queue_status' => 3, 'handle_end_time' => $lcdTime]);
                            $queueHisModel->where(['id' => $insertQueue['id']])->update(['queue_status' => 3, 'handle_end_time' => $lcdTime]);
                        }
                        $queueModel->where('queue_sn', $syncQueueHisList['ID'])->delete();

                    }
                    Cache::set('syncOracleQueueHis' . $branchId, $lcdTime, 0);
                }else{
//                    Cache::set('syncOracleQueueHis' . $branchId, NOW_TIME, 0);
                }
            }
        }
    }

    /**
     * 查询 预约排队的数据,插入排队队列
     * @return \think\Response|\think\response\Json|\think\response\Jsonp|\think\response\Redirect|\think\response\View|\think\response\Xml
     * @throws \Exception
     */
    public function checkQueueOrder()
    {
//        Cache::set('QueueOrder', 0);

        if (!Cache::has('QueueOrder')) {
            Cache::set('QueueOrder', 1, 0);
        }
        $queueOrderTime = Cache::get('QueueOrder');
        if ($queueOrderTime) {
            $queueOrderList = model('QueueOrder')->where(['queue_time' => ['<=', NOW_TIME], 'status' => 1])->order('branchid ASC ,queue_time ASC')->select();
            //print_r($queueOrderList);
            if ($queueOrderList) {
                $branchId = 0;
                foreach ($queueOrderList as $list) {

                    $bisId = $list->bisid;
                    $trueName = $list->truename;
                    $mobile = $list->mobile;

                    if ($branchId != $list->branchid) {
                        $branchId = $list->branchid;
                        $this->getOracleDb($branchId);
                    }

                    if ($this->result['error']) {
                        continue;
                    }

                    //1.获取此业务的编码
                    $bisCode = model('BusinessList')->where('id', $bisId)->value('code') ?: '';

                    //2.获取排队机上的业务id
                    $serviceId = $this->getRemoteServiceId($branchId, $bisCode);
                    if($this->result['error']){
                        continue;
                    }
                    // 获取编码
                    $sql = "select CODE from QUEUE " .
                        " where SERVICE=$serviceId AND CODE like 'Y%'  order by FCD desc";

                    $remoteQueueCode = $this->oracleDb->query($sql);

                    if (empty($remoteQueueCode)) {

                        $sql = "select CODE  from QUEUE_HISTORY " .
                            " where SERVICE=$serviceId AND CODE like 'Y%' AND FCD between to_date('" . date('Y-m-d ') . "00:00:00','yyyy-mm-dd hh24:mi:ss') " .
                            " and to_date('" . date('Y-m-d ') . "23:59:59','yyyy-mm-dd hh24:mi:ss') order by FCD DESC";
                        $queueHisCode = $this->oracleDb->query($sql);

                        if ($queueHisCode) {
                            $nextQueueCode = ++$queueHisCode['0']['CODE'];
                        } else {
                            $nextQueueCode = 'Y001';
                        }
                    } else {
                        $nextQueueCode = ++$remoteQueueCode['0']['CODE'];
                    }

                    //获取时间
                    //查看有无贵宾号
                    $sql = "select to_char(FCD,'yyyy-mm-dd hh24:mi:ss') FCDFORMATE  from QUEUE " .
                        " where SERVICE=$serviceId and CODE like 'Y%' order by FCD DESC";
                    $remoteQueueFcd = $this->oracleDb->query($sql);

                    if (empty($remoteQueueFcd['0']['FCDFORMATE'])) { //没有贵宾号，查找最早的普通号

                        $sql = "select to_char(FCD,'yyyy-mm-dd hh24:mi:ss') FCDFORMATE  from QUEUE " .
                            " where SERVICE=$serviceId and CODE not like 'Y%' and rownum = 1  order by FCD ASC";
                        $remoteQueueNoyFcd = $this->oracleDb->query($sql);

                        if (empty($remoteQueueNoyFcd['0']['FCDFORMATE'])) {  //没有普通号，则取预约时间
                            $queueOrderPrevTime = $list['queue_time'];
                        } else {  // 有普通号，则排在普通号之前

                            $queueOrderPrevTime = strtotime($remoteQueueNoyFcd['0']['FCDFORMATE']) - 1000;
                        }
                    } else {  //有贵宾号  跟在前面一个贵宾号后面

                        $queueOrderPrevTime = strtotime($remoteQueueFcd['0']['FCDFORMATE']) + 1;
                    }


                    $i = 0;
                    do {
                        $remoteQueueId = get_uuid(32);
                        $remoteQueueExits = $this->oracleDb->table('QUEUE')->find($remoteQueueId);
                        $i++;
                        if ($i > 5) {
                            return '';
//                            return ajax_return_error('队列id生成失败');
                        }
                    } while ($remoteQueueExits);

                    $insertOracleQueueSql = "insert into QUEUE(ID,CODE,SERVICE,NETWORK,APPOINTMENT, ACD,FCD) values('$remoteQueueId','$nextQueueCode',$serviceId,0,1111111,
                          to_date('" . date("Y-m-d H:i:s", NOW_TIME) . "','yyyy-mm-dd hh24:mi:ss'),
                          to_date('" . date("Y-m-d H:i:s", $queueOrderPrevTime) . "','yyyy-mm-dd hh24:mi:ss'))";
                    $boolean = $this->oracleDb->execute($insertOracleQueueSql);
                    if ($boolean) {
                        model('Queue')->insert([
                            'queue_sn' => $remoteQueueId,
                            'queue_code' => $nextQueueCode,
                            'branchid' => $branchId,
                            'serviceid' => $serviceId,
                            'bisid' => $bisId,
                            'type' => 1,  //在线排队
                            'uid' => $list->uid,
                            'truename' => $trueName,
                            'mobile' => $mobile,
                            'queue_time' => NOW_TIME,
                            'create_time' => NOW_TIME
                        ]);

                    }

                    $openid = model('Member')->where(['uid' => $list->uid])->value('openid');

                    //排队人数
//                    $waitNum = $this->oracleDb->table('QUEUE')->where(['service' => $serviceId])->count('1') ?: 0;
                    //新需求 网上预约的用户直接插队办理
                    $waitNum = 0;

                    //获取正在受理的编号
                    $sql = "select A.CODE  from QUEUE_HISTORY A,QUEUE_HISTORY B " .
                        " where  A.ID=B.ID AND A.service=$serviceId AND A.SSD=B.LCD AND A.SSD between to_date('" . date('Y-m-d ') . "00:00:00','yyyy-mm-dd hh24:mi:ss') " .
                        " and to_date('" . date('Y-m-d ') . "23:59:59','yyyy-mm-dd hh24:mi:ss') order by A.SSD DESC";
                    $queueHisInfo = $this->oracleDb->query($sql);
                    $queueingCode = '未叫号';
                    if ($queueHisInfo) {
                        $queueingCode = $queueHisInfo['0']['CODE'];
                    }

                    $wechatAuth = new \WechatAuth(Config::get('weixin.appId'), Config::get('weixin.appSecret'));
                    $wechatAuth->getAccessToken();

                    $data = array(
                        'first' => array('value' => "您好,您已成功排队", 'color' => "#00CD00"),
                        'keyword1' => array('value' => $list['bisname'], 'color' => '#EE5C42'),
                        'keyword2' => array('value' => date('Y-m-d H:i', $list['queue_time']), 'color' => '#030303'),
//                        'keyword3' => array('value' => $waitNum, 'color' => '#EE9A00'),
                        'remark' => array('value' => $waitNum <= 1 ? '您的预约编号是' . $nextQueueCode . ',请马上到窗口办理！' : '您的预约编号是' . $nextQueueCode . ',请耐心等待！', 'color' => '#030303'),
                    );
                    $result = $wechatAuth->doSendTpl($openid, '9eKcJnFTJ3eVA8rvgKSybYn_MBF0Qj9Q0bL7mZ1TLIY', 'http://bhgt.jslcwy.com/#/registerDone', $data);
                    file_put_contents('./3.txt', date('Y-m-d H:i:s') . ' ：' . json_encode($result) . PHP_EOL, FILE_APPEND);
                    model('QueueOrder')->where(['id' => $list['id']])->update(['status' => 2]);
                }
            }
            Cache::set('QueueOrder', NOW_TIME);
            return '';
        }

    }

    public function deleteQueue()
    {
        // 获取当前请求的ip地址
        if (Request::instance()->ip() == '116.62.62.56') {
            //$startTime = strtotime(date('Y-m-d ', NOW_TIME) . '00:00:00');
            //$endTime = strtotime(date('Y-m-d ', NOW_TIME) . '04:00:00');
            //if (NOW_TIME >= $startTime && NOW_TIME <= $endTime) {
            model('Queue')->where(['queue_time' => ['<', NOW_TIME]])->delete();
            //}
        }
        return;
    }


}
